package utils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Created by Admin on 2016/3/16.
 */
public class KeyCode {


    private static final char[] DIGITS_LOWER =
            {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
    private static final char[] DIGITS_UPPER =
            {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};

    public static String getMd5Value(String info) {
        MessageDigest digest;
        try {
            digest = MessageDigest.getInstance("MD5");
            byte[] hash = digest.digest(info.getBytes("utf-8"));
            return new String(encodeHex(hash,DIGITS_LOWER));

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String getSHAValue(String info) {

        MessageDigest digest;
        try {
            digest = MessageDigest.getInstance("SHA-256");
            byte[] hash = digest.digest(info.getBytes("utf-8"));
            return new String(encodeHex(hash,DIGITS_LOWER));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }

    }


    protected static char[] encodeHex(final byte[] data, final char[] toDigits) {
        final int l = data.length;
        final char[] out = new char[l << 1];
        // two characters form the hex value.
        for (int i = 0, j = 0; i < l; i++) {
            out[j++] = toDigits[(0xF0 & data[i]) >>> 4];
            out[j++] = toDigits[0x0F & data[i]];
        }
        return out;
    }

  /*  public static String getSHAValue(String info){
        try {
            MessageDigest sha = MessageDigest.getInstance("SHA-256");
            sha.update(info.getBytes("UTF-8"));
            StringBuffer buffer = new StringBuffer();
            byte [] result = sha.digest(info.getBytes("UTF-8"));
            for (byte b : result) {
                int number = b & 0xff;//不按标准加密
                //转换成16进制
                String numberStr = Integer.toHexString(number);
                if (numberStr.length()==1) {
                    buffer.append("0");
                }
                buffer.append(numberStr);
            }
            return buffer.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
    }*/
}
